package com.hd.trans.ui.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.drawable.Drawable
import android.media.MediaScannerConnection
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.TranslateAnimation
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.ViewSwitcher
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.binding.visible
import com.hd.trans.common.Constants
import com.hd.trans.common.interf.Callback
import com.hd.trans.databinding.ActivityPictureTransResultBinding
import com.hd.trans.db.DataBaseMgr
import com.hd.trans.db.bean.FileTranslateRecord
import com.hd.trans.db.bean.HuDunLanguage
import com.hd.trans.db.bean.MediaItem
import com.hd.trans.db.bean.TransitionType
import com.hd.trans.files.aty.MediaAlbumActivity
import com.hd.trans.files.bean.MediaOptions
import com.hd.trans.files.bean.MimeType
import com.hd.trans.framework.click.XClickUtil
import com.hd.trans.framework.component.HuDunTimeoutCallback
import com.hd.trans.framework.dialog.LanguageDialog
import com.hd.trans.framework.dialog.LanguageDialogType
import com.hd.trans.framework.dialog.TipsNormalDlg
import com.hd.trans.homefun.EventCode
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.network.component.FileTranslateCallback
import com.hd.trans.network.component.FileTranslateManager
import com.hd.trans.share.AudioTimeFormatUtil
import com.hd.trans.share.DownloadArg
import com.hd.trans.ui.base.AppContextProvider
import com.hd.trans.ui.base.LimitBaseActivity
import com.hd.trans.ui.model.PictureTransModel
import com.hd.trans.utils.AnimationUtil
import com.hd.trans.utils.HDToastUtil
import com.hd.trans.utils.ImageUtil
import com.hd.trans.utils.ImageUtils
import com.hd.trans.utils.PhotoBitmapUtils
import com.hd.trans.utils.ShareUtil
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.TrackerForTrans
import com.hd.trans.widgets.views.DragImageView2
import java.io.File
import java.io.IOException


class PictureTransResultActivity: LimitBaseActivity() {
    private var isVipFlag = true
    private var twoWay: Boolean = false
    private var transTaskId: String? = null//翻译任务ID
    private var fromHistory: Boolean = true
    private var isOriginal: Boolean = true
    private var isFirstTips: Boolean = true
    private var filePath: String? = null
    private var createTime = 0L
    private var drawableOriginal: Drawable? = null
    private var drawableTrans: Drawable? = null
    private var transFilePath: String? = null
    private var fileTranslateRecord: FileTranslateRecord? = null
    lateinit var mDataBinding: ActivityPictureTransResultBinding
    lateinit var mDataModel: PictureTransModel

    override fun getLayoutId(): Int {
        return R.layout.activity_picture_trans_result
    }

    private val fileTranslateManager by lazy {
        FileTranslateManager().apply {
            setFileTranslateCallback(object : FileTranslateCallback {
                override fun startTranslate() {
                    mDataBinding.tvTipsChangePic.visible = false
                    showLoadingDialog("创建任务")
                }

                override fun onTaskId(taskId: String?) {
                    transTaskId = taskId
                }

                override fun onTaskStatus(
                    status: String?,
                    estimatedTime: Long,
                    pendingCount: Int,
                    progress: Int,
                ) {
                    if("pending" == status) {
                        /*if(estimatedTime > 0){
                            setLoadingTips("预估:${AudioTimeFormatUtil.formatMin(estimatedTime)}")
                        }else */
                        if (pendingCount >= 0) {
                            //setLoadingTips("排队中：$pendingCount")
                            setLoadingTips("等待中...")
                        }
                    }else if ("running" == status || "success" == status) {
                        setLoadingTips("翻译 ${progress}%")
                    }else if ("downloading" == status) {
                        setLoadingTips("下载中...")
                    }
                }

                override fun onTranslateCompleted(
                    originalContent: String?,
                    transContent: String?,
                    fromLangCode: String?,
                    toLangCode: String?,
                    status: Boolean,
                ) {
                }

                override fun onTranslateFailed(code: Int, msg: String?) {
                    hideLoadDialog()
                    if(code == Constants.ResponseCode.ERROR_IS_DANGER){
                        isDangerTipDialog.show(supportFragmentManager, "isDangerTipDialog")
                    }else if(transTaskId != null){
                        showFailureTips()
                    }
                }

                override fun onDownloadStart(downloadArg: DownloadArg?) {
                    //setLoadingTips("下载中")
                }
                override fun onDownloadProgress(downloadArg: DownloadArg?, progress: Int) {
                    /*val percentage = DecimalFormat("00").format(progress)
                    setLoadingTips("下载中:$percentage%")*/
                }
                override fun onDownloadError(downloadArg: DownloadArg?) {
                    hideLoadDialog()
                    if(transTaskId != downloadArg?.taskId){
                        showFailureTips()
                    }
                }
                override fun onDownloadComplete(downloadArg: DownloadArg?) {
                    if(transTaskId != downloadArg?.taskId){
                        return
                    }
                    downloadArg?.let { arg ->
                        if (XClickUtil.isFastDoubleClick(mDataBinding.ivPicture, XClickUtil.INTERVAL_MILLIS.toLong())) {
                            return
                        }
                        hideLoadDialog()
                        var result = true
                        val it: Iterator<String> = arg.targetFileAbsPaths.iterator()
                        while (it.hasNext()) {
                            val filePath: String = it.next()
                            if (filePath != null) {
                                if(!File(filePath).exists()){
                                    result = false
                                }
                            }
                        }
                        if(!result){
                            //下载文件缺失
                            showFailureTips()
                            return
                        }
                        //创建记录
                        makeRecord(arg)
                        consumeFreeTrial()
                        transFilePath = arg.targetFileAbsPaths[0]
                        Log.i("transFilePath", "$transFilePath")
                        mXHandler.post {
                            drawableTrans = null
                            setImageDrawableByFilePath(false)
                        }

                        if(!isVipFlag){
                            mXHandler.post {
                                mDataBinding.tvTipsChangePic.text = resources.getString(R.string.trans_unlock_all)
                                mDataBinding.tvTipsChangePic.visible = true
                                doShakeAnimation()
                            }
                        }else if(isFirstTips){
                            isFirstTips = false
                            mXHandler.post {
                                mDataBinding.tvTipsChangePic.text = resources.getString(R.string.trans_change_original_or_trans)
                                mDataBinding.tvTipsChangePic.visible = true
                                mDataBinding.llTipsClose.visible = true
                                doShakeAnimation()
                            }
                        }
                        if (isVip()){
                            mXHandler.post {
                                ToastUtils.showNormal(resources.getString(R.string.fanyi_success_tip2))
                            }
                        }
                    }
                }
            })
        }
    }

    private fun showFailureTips() {
        failureTipDialog.show(supportFragmentManager, "failureTipDialog")
    }

    private fun makeRecord(downloadArg: DownloadArg) {
        if(fileTranslateRecord == null){
            fileTranslateRecord = FileTranslateRecord()
            fileTranslateRecord?.apply {
                createTime = System.currentTimeMillis()
                updateTime = createTime
                fileName = "拍照翻译_${AudioTimeFormatUtil.formatCreateTime1(createTime)}"
                textLanguageFrom = mDataModel.languageFrom.value
                textLanguageTo = mDataModel.languageTo.value
                fileLanguageFrom = mDataModel.languageFrom.value
                fileLanguageTo = mDataModel.languageTo.value
                originalFilePath = filePath
                translateFilePath = downloadArg.targetFileAbsPaths[0]
                originalText = downloadArg.targetFileAbsPaths[1]
                translateText = downloadArg.targetFileAbsPaths[2]
                inpaintedFilePath = downloadArg.targetFileAbsPaths[3]
                metaFilePath = downloadArg.targetFileAbsPaths[4]
            }
            DataBaseMgr.getInstance().addFileTranslateRecord(fileTranslateRecord)
        }else{
            fileTranslateRecord?.apply {
                updateTime = System.currentTimeMillis()
                textLanguageFrom = mDataModel.languageFrom.value
                textLanguageTo = mDataModel.languageTo.value
                fileLanguageFrom = mDataModel.languageFrom.value
                fileLanguageTo = mDataModel.languageTo.value
                originalFilePath = filePath
                translateFilePath = downloadArg.targetFileAbsPaths[0]
                originalText = downloadArg.targetFileAbsPaths[1]
                translateText = downloadArg.targetFileAbsPaths[2]
                inpaintedFilePath = downloadArg.targetFileAbsPaths[3]
                metaFilePath = downloadArg.targetFileAbsPaths[4]
            }
            DataBaseMgr.getInstance().updateFileTranslateRecord(fileTranslateRecord)
        }

    }

    companion object {

        @JvmStatic
        var productId: Int = -1
        @JvmStatic
        var userId: String = ""
        @JvmStatic
        var callback: Callback? = null

        @JvmStatic
        fun open(context: Context, filePath: String?, createTime: Long, listener: LimitUseListener?, callback: Callback? = null) {
            limitListener = listener
            this.callback = callback
            val intent = Intent(context, PictureTransResultActivity::class.java)
            intent.putExtra("filePath", filePath)
            intent.putExtra("createTime", createTime)
            context.startActivity(intent)
        }
        @JvmStatic
        fun open(
            context: Context,
            filePath: String?,
            createTime: Long,
            productId: Int,
            userId: String,
            listener: LimitUseListener?,
            callback: Callback? = null) {
            limitListener = listener
            this.productId = productId
            this.userId = userId
            this.callback = callback
            val intent = Intent(context, PictureTransResultActivity::class.java)
            intent.putExtra("filePath", filePath)
            intent.putExtra("createTime", createTime)
            context.startActivity(intent)
        }
    }

    private fun checkPermissions(callback: () -> Unit) {
        val permissions = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE)

        val isIntercept = limitListener?.interceptPermission(this@PictureTransResultActivity,
            EventCode.PERMISSION_STORAGE,
            permissions) {
            callback.invoke()
        }?:false

        if (!isIntercept) {
            //APP没有拦截，需要自己处理权限
            permissionUtil.checkIsHavePermission(this@PictureTransResultActivity, permissions) {
                callback.invoke()
            }
        }
    }

    override val pageType: EventCode
        get() = EventCode.CAMERA_TRANS

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        super.initViewsAndEvents(savedInstanceState)
        //视图埋点
        TranslationInterior.getTrackerListener().view("${TrackerForTrans.PZFY}拍照结果页面")
        filePath = intent.getStringExtra("filePath")
        Log.e("PictureTransResult","filePath = $filePath")
        createTime = intent.getLongExtra("createTime",0L)
        fromHistory = createTime > 0

        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_picture_trans_result)
        mDataModel = ViewModelProvider(this).get(PictureTransModel::class.java)

        if(productId != -1 && !TextUtils.isEmpty(userId)){
            fileTranslateManager.setProductInfo(productId, userId)
        }

        initSwitcher()
        initView()
        initData()
    }

    private fun showLoadingDialog(text: String?) {
        showLoadDialog(text, object : HuDunTimeoutCallback(5*60*1000) {
            //如果是互盾超时，直接隐藏
            override fun onTimeOut() {
                hideLoadDialog()
                showFailureTips()
            }
        }) {
            //用户手动点击取消回调
            this.transTaskId = null
            if(!fromHistory && (drawableOriginal == null || drawableTrans == null)){
                toCamera()
            }
            ToastUtils.showNormal(getString(R.string.trans_canceled))
        }
    }

    override fun hideLoadDialog() {
        fileTranslateManager.cancelQueryTask()
        super.hideLoadDialog()
    }

    override fun onResume() {
        super.onResume()
        if(isVipFlag != isVip()){
            isVipFlag = isVip()
            drawableTrans = null
            mDataBinding.tvTipsChangePic.text = resources.getString(R.string.trans_change_original_or_trans)

            setImageDrawableByFilePath(false)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataModel.languageFrom.removeObservers(this)
        mDataModel.languageTo.removeObservers(this)
        mDataModel.operateRecord.removeObservers(this)
    }

    override fun onViewClick(v: View?) {
        if(mDataBinding.llTipsClose.visible){
            mDataBinding.llTipsClose.visible = false
        }
        when(v){
            mDataBinding.ivBack -> finish()
            mDataBinding.lyFrom -> showSelectLanguageDialog(true)
            mDataBinding.lyTo -> showSelectLanguageDialog(false)
            mDataBinding.ivSwitch -> showTranslateAnimation()
            mDataBinding.ivPicture -> {
                if(transFilePath == null) return

                if(isVipFlag || isExample() || isOriginal){
                    setImageDrawableByFilePath(!isOriginal)
                    val tips = if(isVipFlag || isExample()){
                        mDataBinding.tvTipsChangePic.visible = false
                        resources.getString(R.string.trans_change_original_or_trans)
                    }else{
                        mDataBinding.tvTipsChangePic.visible = true
                        resources.getString(R.string.trans_unlock_all)
                    }
                    mDataBinding.tvTipsChangePic.text = tips
                }else{
                    intercept(title = "拍照翻译_查看结果")
                }

            }
            //重拍
            mDataBinding.btnTakePicture -> {
                toCamera()
            }
            //导入图片
            mDataBinding.btnPhotoAlbum -> {
                checkPermissions {
                    //埋点
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.PZFY, TrackerForTrans.AlbumUpload)
                    choosePhoto()
                }
            }
            //保存相册
            mDataBinding.btnSavePic -> {
                if(!intercept(title = "拍照翻译_保存到相册")){
                    checkPermissions {
                        mDataBinding.btnSavePic.postDelayed({
                            //ImageUtil.save2Gallery(if(isOriginal) filePath!! else transFilePath!!)
                            val savePath = saveBitmapFromView(mDataBinding.llSavePhoto)
                            if (!TextUtils.isEmpty(savePath)) {
                                MediaScannerConnection.scanFile(
                                    AppContextProvider.getContext(),
                                    arrayOf(savePath),
                                    null, null
                                )
                                ToastUtils.showNormal("已保存到相册")
                            }
                        },200)
                    }
                }
            }
            //编辑
            mDataBinding.btnEditPic -> {
                if(!intercept(title = "拍照翻译_编辑")){
                    fileTranslateRecord?.let {
                        TextFileTranResultActivity.open(this@PictureTransResultActivity, it.createTime, limitListener)
                    }
                }
            }
            //分享
            mDataBinding.btnSharePic -> {
                if(intercept(title = "拍照翻译_分享")){
                    ShareUtil.shareFile(
                        activity,
                        File(if(isOriginal) filePath!! else transFilePath!!),
                        activity.getString(R.string.share_file)
                    )
                }
            }

        }
    }

    private fun toCamera() {
        if(callback != null){
            callback?.onCallback()
        }else{

            CameraHomeActivity.open(this@PictureTransResultActivity, limitListener)
        }
        finish()
    }


    /**
     * 从相册中选择图片
     */
    private fun choosePhoto() {
        val options: MediaOptions = MediaOptions.build(100)
            .setMax(1)
            .setMin(1)
            .setMediaType(MediaOptions.TYPE_IMAGE)
            .setIncludeMimeType(MimeType.JPEG, MimeType.PNG, MimeType.HEIC)
        val intent = Intent(this, MediaAlbumActivity::class.java)
        intent.putExtra(MediaAlbumActivity.TAG_MEDIA_OPTIONS, options)
        startActivityForResult(intent, TransitionType.PHOTO)
    }

    private fun initView() {
        mDataBinding.run {
            click = this@PictureTransResultActivity
            ivAppIcon.setImageResource(TranslationInterior.getLogoResId())
            tvAppName.text = AppContextProvider.getContext().getString(R.string.sdk_name)
            try {
                val ims = AppContextProvider.getContext().resources.assets.open("icon_qr_code.png")
                val drawable = Drawable.createFromStream(ims, null)
                ivCode.setImageDrawable(drawable)
                llCode.visibility = View.VISIBLE
            } catch (e: IOException) {
                llCode.visibility = View.GONE
                e.printStackTrace()
            }

            tvTipsChangePic.visible = fromHistory
            llTipsClose.visible = fromHistory
            isFirstTips = !fromHistory
            if(fromHistory){
                doShakeAnimation()
            }
        }
    }

    private fun doShakeAnimation(){
        mXHandler.postDelayed({
            AnimationUtil.shake(mDataBinding.tvTipsChangePic, 1.0f, 1.0f, 2f, 800L)
            AnimationUtil.shake(mDataBinding.llTipsClose, 1.0f, 1.0f, 2f, 800L)
        },500)
    }

    private fun initData() {
        /**
         *  监听页面数据变化(语言改变，状态改变)
         */
        mDataModel.languageFrom.observe(this
        ) { huDunLanguage: HuDunLanguage? ->
            if (huDunLanguage != null) {
                mDataBinding.tvFrom.text = huDunLanguage.name
            }
        }
        mDataModel.languageTo.observe(this
        ) { huDunLanguage: HuDunLanguage? ->
            if (huDunLanguage != null) {
                dualIdentityLang(huDunLanguage)
                mDataBinding.tvTo.text = huDunLanguage.name
            }
        }

        mDataModel.operateRecord.observe (this){
            fileTranslateRecord = it
            filePath = it.originalFilePath
            transFilePath = it.translateFilePath

            mDataModel.setLanguageFrom(it.fileLanguageFrom)
            mDataModel.setLanguageTo(it.fileLanguageTo)

            setImageDrawableByFilePath(true)
        }

        val fromLangName = PreferenceMgr.getInstance().translatePreference.fileFromLanguage
        val toLangName = PreferenceMgr.getInstance().translatePreference.fileToLanguage
        mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName))
        mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName))

        if(!fromHistory){
            setImageDrawableByFilePath(true)
            executeTrans()
        }else{
            mDataModel.getFileTranslateRecordByTime(createTime)
        }

    }

    private fun setImageDrawableByFilePath(isOriginal: Boolean){
        val drawable = if(isOriginal) drawableOriginal else drawableTrans
        drawable?.let {
            mDataBinding.ivPicture.setImageDrawable(it)
            this.isOriginal = isOriginal
            return
        }

        val file = (if(isOriginal) filePath else transFilePath) ?: return
        if (File(file).exists()) {
            val drawable = PhotoBitmapUtils.path2Drawable(this@PictureTransResultActivity, file, !isExample() && !isOriginal && !isVipFlag)
            if(isOriginal){
                drawableOriginal = drawable
            }else{
                drawableTrans = drawable
            }
            this.isOriginal = isOriginal
            mDataBinding.ivPicture.setImageDrawable(drawable)
            if(drawable == null){
                ToastUtils.showNormal("图片加载失败")
            }
        }
    }

    private fun isExample(): Boolean{
        return filePath?.contains("example.png") == true
    }

    /**文件翻译*/
    private fun executeTrans(){
        fileTranslateManager.fileTranslate(
            mDataModel.languageFrom.value?.fileRecognitionCode!!,
            mDataModel.languageTo.value?.translateCode!!,
            filePath!!,"auto",1,0, "")
    }

    private fun initSwitcher() {
        //需要先设置转换工厂否则会报错
        mDataBinding.ivPicture.setFactory(SwitcherFactory(this@PictureTransResultActivity))
        mDataBinding.ivPicture.inAnimation = AnimationUtils.loadAnimation(
            this,
            android.R.anim.fade_in
        )
        mDataBinding.ivPicture.outAnimation = AnimationUtils.loadAnimation(
            this,
            android.R.anim.fade_out
        )
    }

    private val isDangerTipDialog by lazy {
        TipsNormalDlg.newInstance(TipsNormalDlg.TipsDlgData.Builder()
            .content(getString(R.string.trans_content_error))
            .cancelStr(resources.getString(R.string.cancel))
            .okStr(getString(R.string.trans_re_trans))
            .canceledOnTouchOutside(false)
            .build()).apply {
            setOnPositiveClick {
                executeTrans()
            }
            setOnNegativeClick {
                if(!fromHistory && (drawableOriginal == null || drawableTrans == null)){
                    toCamera()
                }
            }
        }
    }

    private val failureTipDialog by lazy {
        TipsNormalDlg.newInstance(TipsNormalDlg.TipsDlgData.Builder()
            .content(getString(R.string.trans_translation_failed))
            .cancelStr(resources.getString(R.string.cancel))
            .okStr(getString(R.string.trans_re_trans))
            .canceledOnTouchOutside(false)
            .build()).apply {
            setOnPositiveClick {
                executeTrans()
            }
            setOnNegativeClick {
                if(!fromHistory && (drawableOriginal == null || drawableTrans == null)){
                    toCamera()
                }
            }
        }
    }

    private fun dualIdentityLang(toLang: HuDunLanguage){
        twoWay = if(!TextUtils.isEmpty(toLang.fileRecognitionCode)){
            mDataBinding.ivSwitch.setImageResource(R.mipmap.icon_change)
            true
        }else{
            mDataBinding.ivSwitch.setImageResource(R.mipmap.icon_trans_dx)
            false
        }
    }

    /**选择语言弹框*/
    private fun showSelectLanguageDialog(isFrom: Boolean) {

        val dialog = LanguageDialog(
            mDataModel.languageFrom.value!!,
            mDataModel.languageTo.value!!,
            isFrom, LanguageDialogType.FILE, LanguageDialogType.TO_FILE_FILTRATION)
        dialog.show(supportFragmentManager, "LanguageDialog")
        dialog.setOnLanguageChangedListener(object : LanguageDialog.OnLanguageChangedListener{
            override fun onLanguageChanged(
                fromLanguage: HuDunLanguage,
                toLanguage: HuDunLanguage,
                selectedLanguage: HuDunLanguage,
            ) {
                mDataModel.setLanguageFrom(fromLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveTansFromLanguage(fromLanguage.name)
                mDataModel.setLanguageTo(toLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveTansToLanguage(toLanguage.name)

                if(!intercept(true)){
                    executeTrans()
                }
            }

        })
    }

    /**
     * 互换语种动画
     */
    private fun showTranslateAnimation() {
        if(!twoWay){
            ToastUtils.showNormal("${mDataModel.languageTo.value?.name}暂不支持双向翻译")
            return
        }
        if ("自动检测" == mDataModel.languageFrom.value?.name) {
            return
        }
        val ta1 = TranslateAnimation(0f, (mDataBinding.lyFrom.width + mDataBinding.ivSwitch.width).toFloat(), 0f, 0f)
        ta1.duration = 600
        ta1.fillAfter = true
        mDataBinding.lyFrom.startAnimation(ta1)
        mDataBinding.lyFrom.bringToFront()
        val ta2 = TranslateAnimation(0f, (-mDataBinding.lyTo.width - mDataBinding.ivSwitch.width).toFloat(), 0f, 0f)
        ta2.duration = 600
        ta2.fillAfter = true
        mDataBinding.lyTo.startAnimation(ta2)
        mDataBinding.lyTo.bringToFront()
        ta1.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                val fromTemp: HuDunLanguage? = mDataModel.languageFrom.value
                mDataModel.setLanguageFrom(mDataModel.languageTo.value)
                mDataModel.setLanguageTo(fromTemp)
                PreferenceMgr.getInstance().translatePreference.saveFileFromLanguage(mDataModel.languageFrom.value?.name)
                PreferenceMgr.getInstance().translatePreference.saveFileToLanguage(mDataModel.languageTo.value?.name)
                animation.cancel()

                if(!intercept(true)){
                    executeTrans()
                }
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        ta2.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
    }

    private fun saveBitmapFromView(view: View): String {
        val w = view.width
        val h = view.height
        var bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        val c = Canvas(bmp)
        view.draw(c) //view印入bmp
        // 缩小图片
        val matrix = Matrix()
        matrix.postScale(1f, 1f) //长和宽放大缩小的比例
        bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, matrix, true)
        return PhotoBitmapUtils.saveSourcePhotoToAlbumDir(bmp)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == TransitionType.PHOTO && resultCode == RESULT_OK) {
            if (data?.hasExtra(MediaAlbumActivity.TAG_RESULT) == false) {
                return
            }
            val list: ArrayList<MediaItem>? = data?.getParcelableArrayListExtra(MediaAlbumActivity.TAG_RESULT)
            if (list?.size == 0) {
                return
            }
            list?.let {
                if(it.size > 0){
                    val filePath = list[0].path
                    if (!TextUtils.isEmpty(filePath)) {
                        var bm = BitmapFactory.decodeFile(filePath)
                        //                int degree = ImageUtil.readPictureDegree(filePath);
                        val degree: Int = ImageUtils.getExifOrientation(filePath)
                        if (degree != 0) { // 旋转照片角度
                            bm = ImageUtils.rotateBitmapByDegree(bm, degree)
                        }
                        /*if (bm != null && bm.width > bm.height) {
                            bm = ImageUtils.rotateBitmapByDegree(bm, 90)
                        }*/
                        processBitmap(bm, false)
                    }
                }
            }

        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 图片压缩处理
     */
    private fun processBitmap(mBitmap: Bitmap?, isExperienced: Boolean) {

        if (mBitmap == null || mBitmap.width < 30) {
            runOnUiThread { HDToastUtil.show("图片尺寸太小或已损坏") }
            return
        }

        ImageUtil.processBitmap(mBitmap){
            filePath = it
            transFilePath = null
            drawableOriginal = null
            drawableTrans = null
            setImageDrawableByFilePath(true)
            executeTrans()
        }
    }

    private class SwitcherFactory(private val context: Context) : ViewSwitcher.ViewFactory {
        override fun makeView(): View {
            val imageView = DragImageView2(context)
            //imageView.setScreen_W(ScreenUtil.getScreenWidth(context))
            //imageView.setScreen_H(ScreenUtil.getScreenHeight(context))
            //imageView.setBackgroundColor(-0x1)
            //imageView.scaleType = ImageView.ScaleType.CENTER
            imageView.layoutParams =
                FrameLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )
            return imageView
        }
    }
}